<script setup lang='ts'>
import type { PlusFormGroupRow } from 'plus-pro-components'
import type { VxeGridProps } from 'vxe-table'

import { useGetDeliveryOrderDetail } from '@fl/api/supplier'
import { FlUpload, SearchForm, SearchTable } from '@fl/components'
import { jsonToArray } from '@fl/utils/fn'
import { cloneDeep } from 'lodash-es'

import { DELIVERY_ORDER_STATE } from './constant'

const id = defineModel<string>('id', { required: true })
const visible = defineModel<boolean>('visible', { required: true })

const initialState = { } as any
const state = ref(cloneDeep(initialState))

const isEdit = computed(() => !!id.value)
const dialogTitle = computed(() => '发货单')

const { data: deliveryOrderDetailData, isLoading: isGetDeliveryOrderDetailLoading } = useGetDeliveryOrderDetail(id)

// #region Form
const formRef = ref()
const isFormLoading = computed(() => isGetDeliveryOrderDetailLoading.value)

const group: PlusFormGroupRow[] = [
    {
        columns: [
            {
                colProps: {
                    span: 12,
                },
                label: '预计发货时间',
                prop: 'estimatedShippingDate',
                valueType: 'text',
            },
            {
                colProps: {
                    span: 12,
                },
                label: '发货说明',
                prop: 'shippingInstructions',
                valueType: 'text',
            },
            {
                colProps: {
                    span: 12,
                },
                label: '物流公司',
                prop: 'logisticsCompany',
                valueType: 'text',
            },
            {
                colProps: {
                    span: 12,
                },
                label: '物流单号',
                prop: 'trackingNumber',
                valueType: 'text',
            },
            {
                colProps: {
                    span: 12,
                },
                label: '发货单附件',
                prop: 'attachmentUrl',
            },
        ],
        title: '发货信息',
    },
    {
        columns: [
            {
                colProps: {
                    span: 24,
                },
                hasLabel: false,
                prop: 'productList',
            },
        ],
        title: '商品信息',
    },
    {
        columns: [
            {
                colProps: {
                    span: 12,
                },
                label: '验收时间',
                prop: 'acceptanceDate',
                valueType: 'text',
            },
            {
                colProps: {
                    span: 12,
                },
                label: '验收附件',
                prop: 'acceptanceAttach',
            },
            {
                colProps: {
                    span: 12,
                },
                label: '验收说明',
                prop: 'acceptanceRemark',
                valueType: 'text',
            },
        ],
        hideInGroup: computed(() => deliveryOrderDetailData.value.deliveryNoteState === DELIVERY_ORDER_STATE.DELIVERED),
        title: '验收信息',
    },
]

const rules = {

}
// #endregion

// #region Table
const gridOptions = computed<VxeGridProps>(() => ({
    columns: [
        { field: 'productName', title: '产品名称', width: 200 },
        { field: 'category', title: '产品类目', width: 200 },
        { field: 'brand', title: '品牌' },
        { field: 'model', title: '型号' },
        { field: 'attribute', title: '规格属性' },
        { field: 'unit', title: '单位' },
        { field: 'quantity', title: '数量' },
        { field: 'quantityShipped', title: '本次发货数量' },
        { field: 'quantityAccepted', title: '本次验收数量' },
    ],
    height: 200,
}))

// function formatPrice({ cellValue }) {
//     return (!cellValue || Number.isNaN(cellValue)) ? '' : `¥${cellValue.toFixed(2)}元`
// }
// #endregion

// #region UI Listener
function cancel() {
    visible.value = false
}

function closed() {
    if (isEdit.value) {
        id.value = ''
    }
    else {
        state.value = cloneDeep(initialState)
        formRef.value.formInstance?.resetFields()
    }
}
// #endregion

watchEffect(() => {
    if (deliveryOrderDetailData.value) {
        const data = cloneDeep(deliveryOrderDetailData.value)
        const attachmentUrl = jsonToArray(data.attachmentUrl).map((item: string, index: number) => ({ name: `附件${index + 1}`, url: item }))
        const acceptanceAttach = jsonToArray(data.acceptanceAttach).map((item: string, index: number) => ({ name: `附件${index + 1}`, url: item }))
        Object.assign(state.value, data, {
            acceptanceAttach,
            attachmentUrl,
        })
    }
})
</script>

<template>
    <PlusDialog v-model="visible"
                :title="dialogTitle"
                width="1200"
                close-on-press-escape
                @cancel="cancel"
                @closed="closed"
    >
        <el-skeleton v-if="isFormLoading"
                     animated
        />

        <SearchForm v-else
                    ref="formRef"
                    v-model="state"
                    :group="group"
                    :label-width="100"
                    :rules="rules"
                    :has-footer="false"
                    :row-props="{ gutter: 40 }"
        >
            <template #plus-field-attachmentUrl>
                <FlUpload v-model="state.attachmentUrl"
                          tips
                          accept=".doc,.docx,.pdf,.jpg,.jpeg,.png"
                          list-type="text"
                          disabled
                />
            </template>

            <template #plus-field-acceptanceAttach>
                <FlUpload v-model="state.acceptanceAttach"
                          tips
                          accept=".doc,.docx,.pdf,.jpg,.jpeg,.png"
                          list-type="text"
                          disabled
                />
            </template>

            <template #plus-field-productList>
                <div class="w-full">
                    <SearchTable v-bind="gridOptions"
                                 :data="state.products"
                    />
                </div>
            </template>
        </SearchForm>

        <template #footer>
            <div class="mx-auto">
                <el-button @click="cancel">
                    关闭
                </el-button>
            </div>
        </template>
    </PlusDialog>
</template>

<style lang="scss" scoped>
:deep(.el-form-item--default) {
    margin-bottom: 0;
}
</style>
